package router

import (
	"gitee.com/spellbreaker/FogGoService/service"
	"github.com/gin-gonic/gin"
	socketio "github.com/googollee/go-socket.io"
	"log"
	"math/rand"
	"net/http"
	"time"
)

func GinMiddleware(allowOrigin string) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", allowOrigin)
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, Content-Length, X-CSRF-Token, Token, session, Origin, Host, Connection, Accept-Encoding, Accept-Language, X-Requested-With")

		if c.Request.Method == http.MethodOptions {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Request.Header.Del("Origin")

		c.Next()
	}
}

func Start() {
	rand.Seed(time.Now().UnixNano())

	router := gin.New()

	server := socketio.NewServer(nil)

	//连接socket.io时触发函数，校验用户信息
	server.OnConnect("/", service.Connect)

	//创建房间
	server.OnEvent("/", "createRoom", service.CreateRoom)

	//加入房间
	server.OnEvent("/", "joinRoom", service.JoinRoom)

	//在棋盘上悬浮时提示
	server.OnEvent("/", "tryPlay", service.TryPlay)

	//落子
	server.OnEvent("/", "play", service.Play)

	//测试的demo
	server.OnEvent("/", "notice", func(s socketio.Conn, msg string) service.ResultMsg {
		log.Println("notice:", msg)
		s.Emit("reply", "have "+msg)
		return service.ResultMsg{Success: true, Entity: map[string]string{"msg": msg}}
	})

	server.OnError("/", func(s socketio.Conn, e error) {
		log.Println("meet error:", e)
	})

	//玩家断开连接
	server.OnDisconnect("/", service.Disconnect)

	go func() {
		if err := server.Serve(); err != nil {
			log.Fatalf("socketio listen error: %s\n", err)
		}
	}()
	defer server.Close()

	router.Use(GinMiddleware("http://localhost:7456"))
	router.GET("/socket.io/*any", gin.WrapH(server))
	router.POST("/socket.io/*any", gin.WrapH(server))
	router.StaticFS("/public", http.Dir("./asset"))

	if err := router.Run(":8000"); err != nil {
		log.Fatal("failed run app: ", err)
	}
}
